package top.xxyu.app.login.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import top.xxyu.shiro.ShiroUtil;

@Controller
public class MobileLogin {

	@RequestMapping(value = "/login")
	public String login() {
		Subject subject = SecurityUtils.getSubject();
		boolean authenticated = subject.isAuthenticated();

		if (authenticated) {
			return "mobile/admin/index";
		}
		return "mobile/login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(@RequestParam String username, @RequestParam String password, Model model) {
		String msg = null;
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(token);
			if (subject.isAuthenticated()) {
				return "/index";
			}
		} catch (UnknownAccountException e) {
			msg = "用户名/密码错误";
		} catch (IncorrectCredentialsException e) {
			msg = "密码错误";
		} catch (ExcessiveAttemptsException e) {
			msg = "登录失败多次，账户锁定10分钟";
		} catch (AuthenticationException e) {
			msg = "没有此账号";
		}
		SecurityUtils.getSubject().getSession().removeAttribute(ShiroUtil.SESSION_CURRENT_USER);
		model.addAttribute("open", msg);
		return "mobile/login";

	}

	@RequestMapping(value = "/loginOut")
	public String loginOut() {
		SecurityUtils.getSubject().logout();
		return "redirect:/login";
	}
}
